from django import http
from django.shortcuts import render
from django.views.generic.base import View
# Create your view here.
from . models import NewsChannel, Article
from django.core.paginator import Paginator, EmptyPage


class IndexView(View):
    def get(self,request, channel_id=1, page_num=1):
        '''
        新闻列表展示
        :param request:
        :return:
        '''
        try:
            # 获取NewsChannel对象
            newschannel = NewsChannel.objects.get(id=channel_id)
        except NewsChannel.DoesNotExist:
            return http.HttpResponseNotFound('未找到channel_id')
        else:
            # 获取当前频道下的所有类别id
            category_id_list = [category.id for category in newschannel.newscategory_set.all() if category]

        # 查看当前频道喜爱的所有文章 __in 为魔法下划线
        articles = Article.objects.filter(category_id__in=category_id_list).order_by('id')

        # 创建分页器对象
        page_obj = Paginator(articles,3)

        # 获取当前页数据
        try:
            page_articles = page_obj.page(page_num)
        except EmptyPage:
            return http.HttpResponseNotFound('未找到相应的page_num')

        return render(request,'newsapp/index.html',{'articles':page_articles,'channel_id':channel_id}) # 视图调用模板 View——>templates


class DetailView(View):
    def get(self,request,article_id):
        '''
        新闻详情
        :param request:
        :param article_id:
        :return:
        '''
        try:
            article = Article.objects.get(id=article_id)
        except Article.DoesNotExist:
            return http.HttpResponseNotFound('未找到ip对应文章')
        return render(request,'newsapp/detail.html',{'article':article})